#!/usr/bin/env python
# coding=utf-8
# @FileName  :asyncio_wait.py
# @Time      :2024/7/10 14:28
# @Author    :jdz
# @description :
import asyncio


async def foo():
    return 42


async def sleeping():
    await asyncio.sleep(1000)  # 这是一个长时间运行的任务
    return 421


async def main():
    task = asyncio.create_task(foo())
    sleep = asyncio.create_task(sleeping())

    try:
        done, pending = await asyncio.wait([task, sleep], timeout=5, return_when=asyncio.ALL_COMPLETED)
        if task in done:
            print(task.result())
        if sleep in done:
            print(sleep.result())
        else:
            print("Sleep task is still pending due to timeout")
            # 处理超时任务
            sleep.cancel()
            try:
                await sleep
            except asyncio.CancelledError:
                print("Sleep task was cancelled")
    except asyncio.TimeoutError:
        print("Timeout occurred")


if __name__ == '__main__':
    asyncio.run(main())
